<template>
  <!-- 添加或修改入库信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body :close-on-click-modal="false"
             v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="存货编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入存货编码" maxlength="30"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier" clearable
                       style="width: 300px">
              <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入产品名称" maxlength="200"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入产品型号" maxlength="200"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
       <!-- <el-col :span="12">
          <el-form-item label="型号明细" prop="brand">
            <el-input v-model="form.brand" placeholder="请输入产品型号明细" maxlength="200"/>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入计量单位" maxlength="30"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单价" prop="costPriceTax">
            <el-input-number v-model="form.costPriceTax" placeholder="请输入单价" maxlength="30"  @change="updateTotleCost()"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="count">
            <el-input-number v-model="form.count" placeholder="请输入数量" maxlength="30"  @change="updateTotleCost()"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="重量" prop="dun">
            <el-input-number v-model="form.dun" placeholder="请输入重量" maxlength="30"  @change="updateDun()"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="含税总价" prop="costTax">
            <el-input-number v-model="form.costTax" placeholder="请输入含税总价" maxlength="30"  @change="updateDun()"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" v-if="showBtn">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
    import {addAction, getById, updateAction} from '@/api/manage';
    import request from "@/utils/request";
    import moment from 'moment';

    export default {
        name: "GoodsOrderInUpdate",
        dicts: ['goods_supplier'],
        data() {
            return {
                // 遮罩层
                loading: true,
                activeName: "first",
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                  code: [
                    {required: true, message: "产品编码不能为空", trigger: "blur"},
                    {min: 2, max: 50, message: '用户名称长度必须介于 2 和 50 之间', trigger: 'blur'}
                  ],
                  name: [
                    {required: true, message: "产品名称不能为空", trigger: "blur"}
                  ],
                  deptId: [
                    {required: true, message: "产品分类不能为空", trigger: "blur"}
                  ],
                  email: [
                    {required: true, message: "产品型号不能为空", trigger: "blur"}
                  ],
                  count: [
                    {required: true, message: "数量不能为空", trigger: "blur"}
                  ],
                },
                url: {
                    getById: '/goodsOrderIn/goodsOrderIn/',
                    add: '/goodsOrderIn/goodsOrderIn/add',
                    edit: '/goodsOrderIn/goodsOrderIn/editUpdate',
                },
                minus: 0,
                GoodsNameOptionOri: [],
                GoodsNameOptions: [],
                GoodsBrandOptionOri: [],
                GoodsBrandOptions: [],
                GoodsUnitOptionOri: [],
                GoodsUnitOptions: [],
                pickerOptions: {
                    disabledDate: this.disabledDate
                },
                showBtn: true,
            };
        },
        created() {
        },
        methods: {
            selectSupplier(value) {
              let that = this;
              that.$nextTick(() => {
                let arr = that.$refs.myselectSsupplier;
                for (let i = 0; i < arr.length; i++) {
                  if (arr[i].currentValue == value) {
                    that.form.supplierName = arr[i].label;
                  }
                }
              })
            },
            handleView(row) {
                this.showBtn = false;
                this.reset();
                const id = row.id || this.ids;
                getById(this.url.getById, id).then(response => {
                    this.form = response.data;
                     //this.minus = this.form.count - this.form.remainderCount;//查看详情后立即入库会导致库存剩余数量出错
                    this.open = true;
                    this.title = "查看入库信息";
                });
            },
            disabledDate(time) {
                let _now = Date.now();
                let sevenDaysAgo = moment(new Date()).subtract(7, 'days');
                return time.getTime() < new Date(sevenDaysAgo).getTime();
            },
            updateCostTax() {
                let that = this;
                let percent = 1;
                if (that.form.costPrice && that.form.invoiceTax) {
                   /* if (that.form.invoiceTax === "0") {
                        percent = 1.035;
                    } else {
                        percent = 1;
                    }*/
                    let costPriceTax = that.functionNumberMul(that.form.costPrice, percent).toFixed(2);
                    that.$set(that.form, "costPriceTax", costPriceTax);
                    let costTax = that.functionNumberMul(that.form.count, costPriceTax);
                    that.$set(that.form, "costTax", costTax);
                } else {
                    let costPriceTax = 0;
                    that.$set(that.form, "costPriceTax", costPriceTax);
                    let costTax = 0;
                    that.$set(that.form, "costTax", costTax);
                }
            },
            initOrderInDicts() {
                let that = this;
                request({
                    url: '/goodsOrderIn/goodsOrderIn/initOrderInDicts',
                    method: 'get',
                    params: {}
                }).then(res => {
                    // console.log(res)
                    that.GoodsNameOptionOri = res.data.nameList;
                    that.GoodsNameOptions = res.data.nameList;
                    that.GoodsBrandOptionOri = res.data.brandList;
                    that.GoodsBrandOptions = res.data.brandList;
                })
            },
            updateInsertName(val1) {
                let that = this;
                if (val1) {
                    that.GoodsNameOptions = that.GoodsNameOptionOri.filter(item => item.dictLabel.indexOf(val1) > -1)
                } else {
                    that.GoodsNameOptions = that.GoodsNameOptionOri
                }
                that.$set(that.form, "name", val1);
            },
            updateInsertBrand(val1) {
                let that = this;
                if (val1) {
                    that.GoodsBrandOptions = that.GoodsBrandOptionOri.filter(item => item.dictLabel.indexOf(val1) > -1)
                } else {
                    that.GoodsBrandOptions = that.GoodsBrandOptionOri
                }
                that.$set(that.form, "brand", val1);
            },
            updateTotleCost() {
                let that = this;
                if (that.form.count && that.form.costPriceTax) {
                    let totleCost = that.functionNumberMul(that.form.count, that.form.costPriceTax);
                    that.$set(that.form, "costTax", totleCost);
                }
               // that.updateCostTax();
            },
            functionNumberMul(arg1, arg2) {
                var m = 0;
                var s1 = arg1.toString();
                var s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length;
                } catch (e) {
                }
                try {
                    m += s2.split(".")[1].length;
                } catch (e) {
                }
                let c1 = Number(s1.replace(".", ""));
                let c2 = Number(s2.replace(".", ""));
                let c3 = Math.pow(10, m);
                return c1 * c2 / c3;
            },
            updateDun() {
              let that = this;
              if (that.form.dun && that.form.costTax) {
                let totleCost = that.functionCostPriceTax( that.form.costTax,that.form.dun);
                that.$set(that.form, "costPriceTax", totleCost);
              }
            },
            functionCostPriceTax(arg1, arg2) {
              return Math.round(arg1 / arg2 * 100)/100 ;
            },
            selectSupplier(value) {
                let that = this;
                that.$nextTick(() => {
                    let arr = that.$refs.myselectSsupplier;
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].currentValue == value) {
                            that.form.supplierName = arr[i].label;
                        }
                    }
                })
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: null,
                    name: null,
                    brand: null,
                    unit: null,
                    costPrice: null,
                    count: null,
                    remainderCount: null,
                    cost: null,
                    validityTerm: null,
                    buyId: this.$store.getters.userId,
                    buyName: this.$store.getters.nickName,
                    buyDate: new Date(),
                    buyType: "0",
                    reimburse: '0',
                    supplierId: null,
                    supplierName: null,
                    delFlag: null,
                    createBy: null,
                    createTime: null,
                    updateBy: null,
                    updateTime: null,
                    costPriceTax: 0,
                    costTax: 0,
                    remark: null,
                    deptId: this.$store.getters.deptId,
                    deptName: this.$store.getters.deptName,
                };
                this.resetForm("form");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.initOrderInDicts();
                this.showBtn = true;
                this.open = true;
                this.title = "添加入库信息";
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.initOrderInDicts();
                this.showBtn = true;
                const id = row.id || this.ids;
                getById(this.url.getById, id).then(response => {
                    this.form = response.data;
                    //this.minus = this.form.count - this.form.remainderCount;
                    this.open = true;
                    this.title = "修改入库信息";
                });
            },
            /** 提交按钮 */
            submitForm() {
                let that = this;
                that.$refs["form"].validate(valid => {
                    if (valid) {
                        that.GoodsNameOptions = that.GoodsNameOptionOri;
                        that.GoodsBrandOptions = that.GoodsBrandOptionOri
                        if (that.form.id != null) {
                            updateAction(that.url.edit, that.form).then(response => {
                                that.$modal.msgSuccess("修改成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        } else {
                            addAction(that.url.add, that.form).then(response => {
                                that.$modal.msgSuccess("新增成功");
                                that.open = false;
                                that.$emit('ok');
                            });
                        }
                    }
                });
            },
        }
    };
</script>
